package org.jeecg.modules.inspect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inspect.entity.InsTaskItem;
import org.jeecg.modules.inspect.entity.InsTaskRecord;
import org.jeecg.modules.inspect.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 任务记录
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Api(tags="任务记录")
@RestController
@RequestMapping("/inspect/insTaskRecord")
@Slf4j
public class InsTaskRecordController extends JeecgController<InsTaskRecord, IInsTaskRecordService> {
	@Autowired
	private IInsTaskRecordService insTaskRecordService;
	 @Autowired
	 private IInsCardService insCardService;
	 @Autowired
	 private IInsPointService insPointService;
	 @Autowired
	 private IInsTaskService insTaskService;
	@Autowired
	private IInsTaskItemService insTaskItemService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private JdbcTemplate jdbcTemplate;



	/**
	 * 分页列表查询
	 *
	 * @param insTaskRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务记录-分页列表查询")
	@ApiOperation(value="任务记录-分页列表查询", notes="任务记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<InsTaskRecord>> queryPageList(InsTaskRecord insTaskRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InsTaskRecord> queryWrapper = QueryGenerator.initQueryWrapper(insTaskRecord, req.getParameterMap());
		Page<InsTaskRecord> page = new Page<InsTaskRecord>(pageNo, pageSize);
		IPage<InsTaskRecord> pageList = insTaskRecordService.findListPage(page,insTaskRecord);

		//查询名称
//		List<InsTaskRecord> list = insTaskRecordService.list(queryWrapper);
//		Long total = 0l;
		//查询名称
//		if(CollectionUtils.isNotEmpty(list) ){
//			total = (long)list.size();
//			List<String> taskIds = list.stream().map(o -> o.getTaskId()).collect(Collectors.toSet()).stream().collect(Collectors.toList());
//			if(CollectionUtils.isNotEmpty(taskIds)){
//				List<InsTask> tasks = new ArrayList<>();
//				if(taskIds.size()>=1000){
//					for (int i = 0; i < (taskIds.size()%500==0?taskIds.size()/500:taskIds.size()/500+1) ; i++) {
//						List<String> ids = taskIds.subList(i*500, ( (i+1) * 500) > taskIds.size() ? taskIds.size() : (i+1) * 500);
//						List<InsTask> taskList = insTaskService.findToIds(ids);
//						tasks.addAll(taskList);
//					}
//				}else{
//					tasks = insTaskService.findToIds(taskIds);
//				}
//
//				Map<String, String> taskNameByIdVal = tasks.stream().collect(Collectors.toMap(o -> o.getId(), o -> o.getTaskName(), (p, e) -> p));
//				list.forEach(o->{
//					String taskName = taskNameByIdVal.get(o.getTaskId());
//					o.setTaskName(taskName);
//				});
//				//过滤出符合名称查询条件的
//				//按名称查询
//				if(StringUtils.isNotBlank(insTaskRecord.getTaskName())){
//					list = list.stream().filter(o -> StringUtils.isNotBlank(o.getTaskName()) && o.getTaskName().contains(insTaskRecord.getTaskName())).collect(Collectors.toList());
//					if(CollectionUtils.isNotEmpty(list)){
//						total = (long)list.size();
//						list = list.subList(( (pageNo-1)*pageSize ), (pageNo*pageSize)>list.size()?list.size():pageNo*pageSize);
//					}
//				}
//			}
//		}
//		pageList.setTotal(total);
//		pageList.setRecords(list);
//		pageList.setSize(pageSize);
//		pageList.setCurrent(pageNo);
//		pageList.setPages(total % pageSize == 0 ? total / pageSize : total / pageSize + 1);//分页总数


		return Result.OK(pageList);
	}
	 /**
	  * 分页列表查询
	  *
	  * @param insTaskRecord
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "任务记录-分页列表查询")
	 @ApiOperation(value="任务记录-分页列表查询", notes="任务记录-分页列表查询")
	 @GetMapping(value = "/listConnect")
	 public Result<IPage<InsTaskRecord>> queryConnectPageList(InsTaskRecord insTaskRecord,
									   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									   HttpServletRequest req) {
		 insTaskRecord.setIsConnect("是");
		 QueryWrapper<InsTaskRecord> queryWrapper = QueryGenerator.initQueryWrapper(insTaskRecord, req.getParameterMap());
		 Page<InsTaskRecord> page = new Page<InsTaskRecord>(pageNo, pageSize);
		 IPage<InsTaskRecord> pageList = insTaskRecordService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @ApiOperation(value="我的任务记录-分页列表查询", notes="我的任务记录-分页列表查询")
	 @GetMapping(value = "/mList")
	 public Result<IPage<InsTaskRecord>> mList(InsTaskRecord insTaskRecord,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {
		 //获取登录用户信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 //QueryWrapper<InsTaskRecord> queryWrapper = QueryGenerator.initQueryWrapper(insTaskRecord, req.getParameterMap());
		 //queryWrapper.eq("create_by", sysUser.getUsername());
		 //queryWrapper.orderByDesc("create_time");
		 //
		 String deptId = insTaskRecord.getDeptId();
		 List<SysUser> sysUsers = sysUserService.queryByDepIds(Arrays.asList(new String[]{deptId}), "");
		 if(CollectionUtils.isNotEmpty(sysUsers)){
			 List<String> userNames = sysUsers.stream().map(o -> o.getUsername()).collect(Collectors.toList());
			 insTaskRecord.setUserId(String.join(",",userNames)+",");
		 }else{
			 insTaskRecord.setCreateBy(sysUser.getUsername());
		 }
		 Page<InsTaskRecord> page = new Page<InsTaskRecord>(pageNo, pageSize);
		 //IPage<InsTaskRecord> pageList = insTaskRecordService.page(page, queryWrapper);
		 IPage<InsTaskRecord> pageList = insTaskRecordService.mList(page, insTaskRecord);

		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param insTaskRecord
	 * @return
	 */
	@AutoLog(value = "任务记录-添加")
	@ApiOperation(value="任务记录-添加", notes="任务记录-添加")
	//@RequiresPermissions("org.jeecg.modules:ins_task_record:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody InsTaskRecord insTaskRecord) {
		InsTaskItem insTaskItem = insTaskItemService.getById(insTaskRecord.getItemId());
		String submitPointId = insTaskRecord.getPointId();

		if(null != insTaskItem) {
			// 任务巡检: 应巡检点位与提交点位是否一致
			String pointId = insTaskItem.getPointId();
			if(!submitPointId.equals(pointId)) {
				return Result.error("巡检点位与巡检任务不一致！");
			}
		} else {
			// 无任务巡检
		}

		//InsPoint insPoint = insPointService.getById(insTaskRecord.getPointId());
		//
		//InsCard insCard = insCardService.getById(insTaskRecord.getCardId());
		//if(null == insCard) {
		//	// 卡异常
		//}
		insTaskRecordService.saveMulti(insTaskRecord);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param insTaskRecord
	 * @return
	 */
	@AutoLog(value = "任务记录-编辑")
	@ApiOperation(value="任务记录-编辑", notes="任务记录-编辑")
	//@RequiresPermissions("org.jeecg.modules:ins_task_record:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody InsTaskRecord insTaskRecord) {
		insTaskRecordService.updateById(insTaskRecord);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务记录-通过id删除")
	@ApiOperation(value="任务记录-通过id删除", notes="任务记录-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:ins_task_record:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		insTaskRecordService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务记录-批量删除")
	@ApiOperation(value="任务记录-批量删除", notes="任务记录-批量删除")
	//@RequiresPermissions("org.jeecg.modules:ins_task_record:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.insTaskRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务记录-通过id查询")
	@ApiOperation(value="任务记录-通过id查询", notes="任务记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<InsTaskRecord> queryById(@RequestParam(name="id",required=true) String id) {
		InsTaskRecord insTaskRecord = insTaskRecordService.getById(id);
		if(insTaskRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(insTaskRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param insTaskRecord
    */
    //@RequiresPermissions("org.jeecg.modules:ins_task_record:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsTaskRecord insTaskRecord) {
        return super.exportXls(request, insTaskRecord, InsTaskRecord.class, "任务记录");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("ins_task_record:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InsTaskRecord.class);
    }


    /**
     * 查询巡检记录报表
     * @return
     */
    @RequestMapping("queryRecordReport")
    public Result<IPage<Map<String,Object>>> queryMsgIssueReport(@RequestParam(name="departIds",required = false)String deptIds,
																 @RequestParam(name="insTime_begin",required = false)String insTime_begin,
																 @RequestParam(name="insTime_end",required = false)String insTime_end,
																 @RequestParam(name="createBy",required = false)String createBy,
                                                                 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        Result<IPage<Map<String, Object>>> result = new Result<>();
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);


        List<Map<String,Object>> msgIssueLists = jdbcTemplate.queryForList(
                " SELECT " +
					" max( UUID() ) AS \"id\", "+
					" max( r.id ) AS \"recordId\", " +
					" max( r.ins_status ) AS \"insStatus\", " +
					" max( r.ins_time ) AS \"insTime\", " +
					" max( r.remark ) AS \"remark\", " +
					" max( r.create_by ) AS \"createBy\", " +
					" max( " +
					" DATE_FORMAT( r.create_time, '%Y-%m-%d' )) AS \"createTime\", " +
					" max( u.realname ) AS \"createByName\", " +
					" max( d.id ) AS \"deptId\", " +
					" max( d.depart_name ) AS \"deptName\" , " +
					" max(rr.count) AS \"allCount\"  " +
					" FROM " +
					" ins_task_record r " +
					" LEFT JOIN sys_user u ON u.username = r.create_by " +
					" LEFT JOIN sys_user_depart ud ON ud.user_id = u.id " +
					" LEFT JOIN sys_depart d ON d.id = ud.dep_id " +
					" LEFT JOIN ( " +
						" SELECT rr.create_by AS \"create_by\", DATE_FORMAT( rr.create_time, '%Y-%m-%d' ) AS \"create_time\", count( 0 ) AS \"count\"  " +
						" FROM ins_task_record rr  " +
						" GROUP BY rr.create_by, DATE_FORMAT( rr.create_time, '%Y-%m-%d' )  " +
					" ) rr on rr.create_by=r.create_by and rr.create_time=DATE_FORMAT( r.create_time, '%Y-%m-%d' )  " +
					" WHERE 1=1 "+
						( StringUtils.isNotBlank(deptIds)?" and instr('"+deptIds+"', d.id)>0 " :"")+
						( StringUtils.isNotBlank(insTime_begin)?" and DATE_FORMAT( r.create_time, '%Y-%m-%d' )>='"+insTime_begin+"' " :"")+
						( StringUtils.isNotBlank(insTime_end)?" and DATE_FORMAT( r.create_time, '%Y-%m-%d' )<='"+insTime_end+"' " :"")+
                        ( StringUtils.isNotBlank(createBy)?" and u.realname like '%"+createBy+"%' " :"")+
					" GROUP BY " +
					" d.depart_name, " +
					" DATE_FORMAT( r.create_time, '%Y-%m-%d' ), " +
					" r.create_by "+
					"ORDER BY " +
					" d.depart_name, " +
					" DATE_FORMAT( r.create_time, '%Y-%m-%d' ) DESC, " +
					" r.create_by  " +
					(pageNo != null && pageSize != null ? " limit " + (pageNo - 1) * pageSize + "," + pageSize : ""));
        Long count = jdbcTemplate.queryForObject(
				"select count(0) from ("+
						" SELECT count(0) FROM " +
						" ins_task_record r " +
						" LEFT JOIN sys_user u ON u.username = r.create_by " +
						" LEFT JOIN sys_user_depart ud ON ud.user_id = u.id " +
						" LEFT JOIN sys_depart d ON d.id = ud.dep_id " +
						" LEFT JOIN ( " +
						" SELECT rr.create_by AS \"create_by\", DATE_FORMAT( rr.create_time, '%Y-%m-%d' ) AS \"create_time\", count( 0 ) AS \"count\"  " +
						" FROM ins_task_record rr  " +
						" GROUP BY rr.create_by, DATE_FORMAT( rr.create_time, '%Y-%m-%d' )  " +
						" ) rr on rr.create_by=r.create_by and rr.create_time=DATE_FORMAT( r.create_time, '%Y-%m-%d' )  " +
						" WHERE 1=1 "+
							( StringUtils.isNotBlank(deptIds)?" and instr('"+deptIds+"', d.id)>0 " :"")+
							( StringUtils.isNotBlank(insTime_begin)?" and DATE_FORMAT( r.create_time, '%Y-%m-%d' )>='"+insTime_begin+"' " :"")+
							( StringUtils.isNotBlank(insTime_end)?" and DATE_FORMAT( r.create_time, '%Y-%m-%d' )<='"+insTime_end+"' " :"")+
							( StringUtils.isNotBlank(createBy)?" and u.realname like '%"+createBy+"%' " :"")+
						" GROUP BY " +
						" d.depart_name, " +
						" DATE_FORMAT( r.create_time, '%Y-%m-%d' ), " +
						" r.create_by "+
						"ORDER BY " +
						" d.depart_name, " +
						" DATE_FORMAT( r.create_time, '%Y-%m-%d' ) DESC, " +
						" r.create_by  "+
					") tt"
                , Long.class);
        page.setTotal(count);
        page.setRecords(msgIssueLists);
        result.setResult(page);
        return result;
    }
}
